package com.ojoin.weixin.core.oauth2.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.web.domain.Pair;
import com.ojoin.trade.common.web.shiro.UsernamePasswordToken;
import com.ojoin.weixin.core.message.model.SendMessage;
import com.ojoin.weixin.core.model.AccessToken;
import com.ojoin.weixin.core.model.Result;
import com.ojoin.weixin.core.oauth2.inteceptor.APPConstants;
import com.ojoin.weixin.core.oauth2.util.RequestUtil;
import com.ojoin.weixin.core.oauth2.util.WeixinUtil;
import com.ojoin.weixin.core.user.model.Staff;
import com.ojoin.weixin.core.user.util.StaffUtil;

/**
 * OAuth2 处理控制器
 */
@Controller
@RequestMapping(value = "wechat")
public class OAuth2Controller {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(OAuth2Controller.class);

	/**
	 * 构造参数并将请求重定向到微信API获取登录信息
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/oauth2" })
	public String Oauth2API(HttpServletRequest request,
			@RequestParam String resultUrl) {

		LogUtils.info(logger,"Oauth2API(HttpServletRequest, String)+自动认证拦截");

		// 此处可以添加获取持久化的数据，如企业号id等相关信息
		String CropId = APPConstants.CORPID;
		String redirectUrl = "";
		if (resultUrl != null) {
			String reqUrl = request.getServerName();
//			reqUrl = reqUrl + "/" + APPConstants.APP_NAME;
			String backUrl = "https://" + reqUrl + "/wechat/oauth2url?oauth2url="
					+ resultUrl;

			LogUtils.info(logger,"backUrl=" + backUrl);

			redirectUrl = oAuth2Url(CropId, backUrl);
		}
		return "redirect:" + redirectUrl;
	}

	/**
	 * 根据code获取Userid后跳转到需要带用户信息的最终页面
	 * 
	 * @param request
	 * @param code
	 *            获取微信重定向到自己设置的URL中code参数
	 * @param oauth2url
	 *            跳转到最终页面的地址
	 * @return
	 */
	@RequestMapping(value = { "/oauth2url" })
	public String Oauth2MeUrl(HttpServletRequest request,
			@RequestParam String code, @RequestParam String oauth2url) {
		AccessToken accessToken = WeixinUtil.getAccessToken(
				APPConstants.CORPID, APPConstants.APPSECRET);
		HttpSession session = request.getSession();
		
		String gourl="/error/unauthorized.html";
		
		if (accessToken != null && accessToken.getToken() != null) {
			Pair<String,String> retP = getMemberGuidByCode(accessToken.getToken(), code,
					APPConstants.AGENTID);
			
			LogUtils.info(logger,"access user is  %s",retP);
			
			if (retP != null) {
				if(retP.first.equals("0")){
					Staff staff = StaffUtil.getStaffByUserId(retP.second, accessToken.getToken());
					//内部登录 session中
				    
				    Subject currentUser = SecurityUtils.getSubject();
					UsernamePasswordToken token = new UsernamePasswordToken("wechat_"+retP.second,IConstDef.loginType_Factor_Wechat);
				    currentUser.login(token);
				    
					session.setAttribute(APPConstants.CURRENT_LOGIN_WECHAT, staff);
					gourl=oauth2url;
				}
			}
		}
		return "redirect:" + gourl;
	}

	/**
	 * 构造带员工身份信息的URL
	 * 
	 * @param corpid
	 *            企业id
	 * @param redirect_uri
	 *            授权后重定向的回调链接地址，请使用urlencode对链接进行处理
	 * @return
	 */
	private String oAuth2Url(String corpid, String redirect_uri) {
		try {
			redirect_uri = java.net.URLEncoder.encode(redirect_uri,
					APPConstants.APP_ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.error("oAuth2Url(String, String)", e);
		}
		String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ corpid
				+ "&redirect_uri="
				+ redirect_uri
				+ "&response_type=code&scope=snsapi_base&state="+APPConstants.TOKEN+"#wechat_redirect";
		LogUtils.info(logger, "oauth2Url=" + oauth2Url);
		return oauth2Url;
	}

	/**
	 * 调用接口获取用户信息
	 * 
	 * @param token
	 * @param code
	 *            返回代码
	 * @param agentId
	 *            应用ID
	 * @return
	 */
	public Pair<String,String> getMemberGuidByCode(String token, String code, int agentId) {
		Result<String> result = WeixinUtil.oAuth2GetUserByCode(token, code, agentId);
		
		//没有关注
		if (result.getErrcode() == "0") {
			if (result.getObj() != null) {
				String access_token = WeixinUtil.getAccessToken(APPConstants.CORPID,
						APPConstants.APPSECRET).getToken();
				// 回复文本消息
				String PostData = SendMessage.STextMsg("hgc|guoting", "", "", "0", "登录用户(userid):"+result.getObj());
				RequestUtil.PostMessage(access_token, "POST", SendMessage.POST_URL,
						PostData);

				return Pair.of("0", result.getObj());
			}
		}else if(result.getErrcode() == "1"){
			if (result.getObj() != null) {
				String access_token = WeixinUtil.getAccessToken(APPConstants.CORPID,
						APPConstants.APPSECRET).getToken();
				// 回复文本消息
				String PostData = SendMessage.STextMsg("hgc|guoting", "", "", "0", "未授权用户(openid):"+result.getObj());
				RequestUtil.PostMessage(access_token, "POST", SendMessage.POST_URL,PostData);

				return Pair.of("1", result.getObj());
			}
		}

		return null;
	}

}
